package com.caiyi.financial.nirvana.sms.service;

import com.caiyi.financial.nirvana.sms.base.service.BaseService;
import com.caiyi.financial.nirvana.sms.entity.SmsPermission;
import com.caiyi.financial.nirvana.sms.entity.SmsRole;
import com.caiyi.financial.nirvana.sms.querybean.MenuBean;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SmsPermissionService extends BaseService<SmsPermission> {

    /**
     * 根据角色查询全部可用权限
     * 补全父节点到列表
     *
     * @param role 角色
     * @return 权限Map
     */
    public List<SmsPermission> queryAllPermissionByRole(SmsRole role) {
        if (role == null) {
            return new ArrayList<>();
        }
        Example example = new Example(SmsPermission.class);
        logger.info("role id : {}, code : {}", role.getId(), role.getPermissionCodes());
        example.createCriteria()
                .andCondition("code in ('" + role.getPermissionCodes().replaceAll(",", "','") + "')");
        List<SmsPermission> all = queryAll();
        List<SmsPermission> auth = queryListByExample(example);
        Map<String, SmsPermission> authMap = new HashMap<>();
        for (SmsPermission item : auth) {
            authMap.put(item.getCode(), item);
        }
        for (SmsPermission item : auth) {
            this.addParent(item, authMap, all);
        }
        auth.clear();
        auth.addAll(authMap.values());
        return auth;
    }

    /**
     * 递归补全父节点
     *
     * @param permission 当前节点
     * @param auths      目标容器
     * @param all        全部菜单 ，减少访问数据库
     */
    private void addParent(SmsPermission permission, Map<String, SmsPermission> auths, List<SmsPermission> all) {
        for (SmsPermission item : all) {
            if (permission.getParent().equals(item.getCode())) {
                if (!auths.containsKey(item.getCode())) {
                    auths.put(item.getCode(), item);
                    this.addParent(item, auths, all);
                }
            }
        }
    }

    /**
     * 补全子节点Code
     *
     * @param parent 父节点CODE
     * @return 新的未被占用的子节点CODE
     */
    public String getNextCode(String parent) {
        Example example = new Example(SmsPermission.class);
        example.createCriteria().andEqualTo("parent", parent);
        example.setOrderByClause("code desc");
        List<SmsPermission> children = this.queryListByExample(example);
        SmsPermission latest = children.size() > 0 ? children.get(0) : null;
        if (latest == null) {
            return parent + "01";
        } else {
            Integer latestNum = Integer.parseInt(latest.getCode().replaceAll("M", ""));
            latestNum++;
            return "M00" + latestNum;
        }
    }

    /**
     * 格式菜单列表
     * 将权限整合为菜单树
     *
     * @param authPermissions 权限
     * @return 菜单列表
     */
    public List<MenuBean> formatMenus(List<SmsPermission> authPermissions) {
        List<MenuBean> result = new ArrayList<>();
        for (SmsPermission item : authPermissions) {
            MenuBean menu = new MenuBean();
            menu.setCode(item.getCode());
            menu.setDesc(item.getDescription());
            menu.setIcon(item.getIcon());
            menu.setName(item.getName());
            menu.setParent(item.getParent());
            menu.setPath(item.getUrl());
            menu.setType(item.getType());
            result.add(menu);
        }
        result.sort((o1, o2) -> {
            int code1 = Integer.parseInt(o1.getCode().replace("M", ""));
            int code2 = Integer.parseInt(o2.getCode().replace("M", ""));
            return code1 - code2;
        });

        MenuBean root = new MenuBean();
        root.setCode("ROOT");
        this.resolveChild(root, result);
        return root.getChildren();
    }

    /**
     * 递归
     * 转移子节点到Parent.Children
     *
     * @param parent          父节点
     * @param authPermissions 全部权限
     */
    private void resolveChild(MenuBean parent, List<MenuBean> authPermissions) {
        for (MenuBean item : authPermissions) {
            if (item.getParent().equals(parent.getCode())) {
                parent.getChildren().add(item);
                this.resolveChild(item, authPermissions);
            }
        }
    }

}
